import request from "../../utils/request"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: null, // 收货地址
    list: [],
    totalAmount: 0
  },
  async onSubmit() {
    if (!this.data.address) {
      wx.showToast({
        title: '请选择收获地址',
        icon: "none"
      })
      return
    }
    const {
      name,
      phone,
      address,
      detailAddress
    } = this.data.address;
    const userId = wx.getStorageSync('userInfo').id;
    const orderItems = this.data.list.map(item => {
      return {
        productSkuId: item.productSku.id,
        quantity: item.quantity,
        // totalPrice: item.productSku.price
      }
    })
    const orderForm = {
      receiverName: name,
      receiverPhone: phone,
      receiverAddress: address + detailAddress,
      // totalAmount: this.data.totalAmount,
      userId,
      couponId: 1,
      orderItems
    };
    const res = await request.post('/orders/create', orderForm);
    console.log(res);
    const orderId = res.data.data.id;
    const openId = wx.getStorageSync('userInfo').openid;
    const payres = await request.post('/pay/create', {
      orderId,
      openId
    })
    wx.requestPayment({
      ...payres.data.data,
      signType: "MD5",
      success: res => {
        console.log(res);
        wx.showToast({
          title: '支付成功',
        })
      },
      fail: err => {
        console.log(err);
        wx.showToast({
          title: '支付失败',
        })
      },
      complete: () => {
        wx.navigateTo({
          url: '/pages/order/order',
        })
      }
    })
    console.log(payres);
  },
  async getDefaultAddress() {
    const userId = wx.getStorageSync('userInfo').id;
    const res = await request.get(`/address/page?is_default=1&userId=${userId}`);
    if (res.data.data.length) {
      this.setData({
        address: res.data.data[0]
      })
    }
    console.log(res.data, "获取默认地址");
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDefaultAddress();
    console.log(wx.getStorageSync('addOrder'), "要结算的商品");
    const list = wx.getStorageSync('addOrder');
    let totalAmount = 0;
    list.forEach(item => {
      totalAmount += (item.productSku.price * item.quantity)
    })
    this.setData({
      list,
      totalAmount
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (wx.getStorageSync('selectAddress')) {
      this.setData({
        address: wx.getStorageSync('selectAddress')
      })
      wx.removeStorageSync('selectAddress')
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})